package com.example.jddjxx.web.service;

import com.example.jddjxx.config.ConfigSite;
import com.example.jddjxx.constant.Site;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.util.FileCopyUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>SiteServiceImpl</p>
 * description
 *
 * @author 邓峰峰
 * @date 8/21/2020 11:56 AM
 */
public class JsonFileSiteService implements SiteService{

    @Value("classpath:config/site.json")
    private Resource resource;


    @Override
    public Map<String, Site> schemeMap() {
        try {
            final File jsonFile = ConfigSite.getConfigSiteJsonFile();
            String json = FileCopyUtils.copyToString(new InputStreamReader(new FileInputStream(jsonFile), StandardCharsets.UTF_8));
            ObjectMapper om = new ObjectMapper();
            final List<Site> sites;
            try {
                sites = om.readValue(json, new TypeReference<List<Site>>() {
                });
            } catch (JsonProcessingException e) {
                e.printStackTrace();
                throw new RuntimeException("site.json格式有误");
            }
            final Map<String, Site> collect = sites.stream().collect(Collectors.toMap(Site::getScheme, Function.identity()));
            return collect;
        } catch (IOException e) {
            e.printStackTrace();
        }
        throw new RuntimeException("site.json不存在");

    }


}
